﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GDGeek;
using NormalBattleIoc;
using Models;

public class TurnSystem : Singleton<TurnSystem>
{



    public FSM fsm_turnsystem = new FSM();

    public List<BattleAction> allaction = new List<BattleAction>();

    public bool allenemydead = false;

    private TurnBattleEventView eventview;

    private CameraShake camerashake;
    // Use this for initialization
    void Start()
    {
        GameObject g = GameObject.Find("TurnBattleEventView");

        eventview = g.GetComponent<TurnBattleEventView>();

        camerashake = GameObject.Find("BattleCamera").GetComponent<CameraShake>();

    }

    public void AddAction( BattleAction  _a  )
    {
        allaction.Add(_a);
    }

    public void NextAction()
    {


        Debug.Log("当前action数量："+allaction.Count);
        //判断  玩家是否全部死亡
        GameObject[] allenemy = GameObject.FindGameObjectsWithTag("Enemy");
        int e = 0;
        for (int i = 0; i < allenemy.Length; i++)
        {
            
            if(allenemy[i].GetComponent<EnemyInBattle>().isDead())
            {
                e++;
            }
        }

        if( e == allenemy.Length)
        {
            allenemydead = true;
            eventview.OpenWinPanel();
            return;
        }



        //判断  玩家是否全部死亡
        GameObject[] allplayer = GameObject.FindGameObjectsWithTag("Player");
        for(int i =0; i< allplayer.Length; i++)
        {
            //allplayer[i].GetComponent<PlayerInBattle>().isDead();
        }

        //判断action列表是否已经空了
        if(allaction.Count == 0)
        {
            WaitSetEnemyAction();
            Debug.Log("本轮Acton执行完毕，转为玩家选择攻击状态");
            //说明  动作列表 已经执行完毕
            //这里需要跳转为玩家操作状态
            PlayerManager.Instance.FSM_System_DoAction_ChangeTo_System_Wait();
            return;
        }

        //先重新排序
        allaction.Sort();

        BattleAction action = allaction[0];
        allaction.Remove(  action );
        //取出第一个元素

        //执行第一个元素
        action.DoAction();
        //下一个turn

        //判断 turnlist是否执行完毕

        //状态转到  等待玩家选择策略状态
    }

    public void WaitSetEnemyAction()
    {
        if(allenemydead)
        {
            return;
        }

        Debug.Log("开始执行WaitSetEnemyAction");
        //判断敌人是否 全部死亡
        GameObject[] allenemy = GameObject.FindGameObjectsWithTag("Enemy");
        for (int i = 0; i < allenemy.Length; i++)
        {
            EnemyInBattle e = allenemy[i].GetComponent<EnemyInBattle>();
            if (e.isDead() == false)
            {
                Debug.LogError("把没有死亡的敌人，添加攻击策略");
                e.FSMSystem_DoAction_ChangeTo_EnemyWait();
                e.CoroutineToEnemySystemDoAction();
            }


        }

    }


    public void ShakeCamera(float s , float tt)
    {
        camerashake.ShakeCamera(s, tt);
    }
    


}
